/**
 * 
 */
package com.wubo.common.io;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP定向代理
 * @author WuBo
 * @CreateDate 2012-2-17
 */
public class HttpDirectedProxy {
	private static Logger logger = LoggerFactory.getLogger(HttpDirectedProxy.class);

	public static void proxy(String queryPath, Map<String, String> paramMap, String method, OutputStream outputStream){
		HttpURLConnection conn = null;
		InputStream is = null;
		BufferedInputStream bis = null;
		try{
			StringBuilder postData = new StringBuilder();
			if(paramMap != null && paramMap.size() > 0){
				postData.append("?");
				Set<String> set = paramMap.keySet();
				int i = 0;
				for(String key : set){
					if(i++ > 0){
						postData.append("&");
					}
					postData.append(key+"=");
					postData.append(URLEncoder.encode(paramMap.get(key), "UTF-8"));
				}
			}
			if("GET".equalsIgnoreCase(method)){
				queryPath += postData.toString();
			}
			logger.debug("QueryPath: "+queryPath);
			URL url = new URL(queryPath);
			conn = (HttpURLConnection) url.openConnection();
			
			conn.setRequestMethod(method);
			conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setDoOutput(true);
			if("POST".equalsIgnoreCase(method)){
				conn.connect();
				OutputStream os = conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(os);
				dos.write(postData.toString().getBytes("UTF-8"));
				dos.close();
			}
			
			is = conn.getInputStream();
			bis = new BufferedInputStream(is);
			try{
				byte[] data = new byte[1024];
				int len = 0;
				while((len = bis.read(data)) != -1){
					outputStream.write(data, 0, len);
				}
				outputStream.flush();
			}finally{
				try{outputStream.close();}catch(Exception e){}
			}
			if(logger.isDebugEnabled()){
				StringBuilder buff = new StringBuilder();
				buff.append("================== Response Head =====================");
				Map<String,List<String>> headFields = conn.getHeaderFields();
				Iterator<String> ite = headFields.keySet().iterator();
				while(ite.hasNext()){ 
					String key = ite.next();
					List<String> value = headFields.get(key);
					buff.append("\n{"+key+":"+value+"}");
				}
				logger.debug(buff.toString());
			}
		}catch(Exception ex){
			logger.error("失败："+queryPath+" - "+ex.getLocalizedMessage());
		}finally{
			try{
				if(bis != null)bis.close();
				if(is != null)is.close();
			}catch(Exception ex){}
			conn.disconnect();
		}
	}
	
}
